package com.mdp.workflow.bus.listener.global;

import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.micro.client.CallBizService;
import com.mdp.workflow.biz.ru.service.ProcinstNodeInfoService;
import com.mdp.workflow.client.service.FlowMsgServiceImpl;
import com.mdp.workflow.client.service.WfSysUserService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 任务节点前置监听处理类
 * @author: Lu Yang
 * @create: 2019-05-04 20:51
 **/
@Component
public class TaskCreatedListener implements FlowableEventListener {

	Log log=LogFactory.getLog(TaskCreatedListener.class);

	
	@Autowired
	private ProcinstNodeInfoService procinstNodeInfoService;

	@Autowired
	private WfSysUserService sysUserService;


	@Autowired
    FlowMsgServiceImpl pushMsgService;



	@Autowired
	CallBizService callBizService;
	
	 public DelegateExecution getExecution(String executionId) {
	        if (executionId != null) {
	            CommandContext commandContext = CommandContextUtil.getCommandContext();
	            if (commandContext != null) {
	                return CommandContextUtil.getExecutionEntityManager(commandContext).findById(executionId);
	            }
	        }
	        return null;
	    }
	

    @Override
    public void onEvent(FlowableEvent event) {
		if(!FlowableEngineEventType.TASK_CREATED.equals(event.getType())){
			return;
		}
		 // 当前节点任务实体
		FlowableEntityEventImpl eventImpl=(FlowableEntityEventImpl)event;
       TaskEntity taskEntity = (TaskEntity) (eventImpl.getEntity());
       DelegateExecution execution=this.getExecution(eventImpl.getExecutionId());
	   if(execution==null){
		   return;
	   }
 		FlowElement element=execution.getCurrentFlowElement();
		if(element instanceof UserTask) {
			UserTask task=(UserTask)element;
		
			if(task.hasMultiInstanceLoopCharacteristics()){
				/**
				 * 另附判断结果类中流程引擎自带可用变量：
					1.nrOfInstances 该会签环节中总共有多少个实例
						2.nrOfActiveInstances 当前活动的实例的数量，即还没有 完成的实例数量。
						3.nrOfCompletedInstances 已经完成的实例的数量
						4.nrOfAgree 同意个数
						5.nrOfDisAgree 不同意个数
					 */
				int completedInstance = (int)execution.getVariable("nrOfCompletedInstances");
				int nrOfInstances = (int)execution.getVariable("nrOfInstances"); 
				execution.setVariable("nrOfAgree", 0);
				execution.setVariable("nrOfDisAgree", 0);
				log.debug("completedInstance"+completedInstance);
				return;
			}else {
				Map<String, Object> flowVars = taskEntity.getVariables();
				String processInstanceId = taskEntity.getProcessInstanceId();

					//subscribeTaskEvent
					//如果有上送restUrl，回调restUrl推送审核数据 
					String restUrl = (String) flowVars.get("restUrl");
					String mainTitle = (String) flowVars.get("mainTitle");
					String subscribeTaskEvent = (String) flowVars.get("subscribeTaskEvent");
					String currentUserid = (String) flowVars.get("currentUserid");
					String currentUsername = (String) flowVars.get("currentUsername");
					String startUserid = (String) flowVars.get("startUserid");
					String taskName = taskEntity.getName();
					if (!StringUtils.isEmpty(restUrl) && subscribeTaskEvent != null && subscribeTaskEvent.contains(event.getType().name())) {
						Map<String, Object> paramMap = new HashMap<String, Object>();

						///processInstance.get
						String bizKey = (String) flowVars.get("bizKey");
						String actId = taskEntity.getTaskDefinitionKey();

						String branchId = taskEntity.getTenantId();
						String eventName = event.getType().name();
						String formId = (String) flowVars.get("formId");
						paramMap.putAll(flowVars);
						paramMap.put("procInstId", processInstanceId);
						paramMap.put("startUserid", startUserid);
						paramMap.put("mainTitle", mainTitle);
						paramMap.put("assignee", taskEntity.getAssignee());
						paramMap.put("assigneeName", taskEntity.getAssignee());
						paramMap.put("actId", actId);
						paramMap.put("taskName", taskName);
						paramMap.put("flowBranchId", branchId);
						paramMap.put("bizKey", bizKey);
						paramMap.put("eventName", eventName);
						paramMap.put("modelKey", execution.getProcessDefinitionId());
						if (!StringUtils.isEmpty(formId)) {
							paramMap.put("formId", formId);
						}
						Tips tips = callBizService.postForTips(restUrl, paramMap);
						if (tips.isOk() == false) {
							throw new BizException(tips);
						}
					}
					//pushMsgService.pushMsg(startUserid, "流程【"+mainTitle+"】,任务【"+taskName+"】已由【"+currentUsername+"】提交");
					pushMsgService.pushTaskMsg(taskEntity.getAssignee(), (String) execution.getVariable("mainTitle"), taskEntity.getName(), (String) execution.getVariable("commentMsg"), (String) execution.getVariable("bizUrl"));
				}
			}

		
	}

    @Override
    public boolean isFailOnException() {
        return true;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}